package qf.sail.controller;


import qf.sail.contents.CodeMsg;
import qf.sail.entity.Account;
import qf.sail.service.AccountService;
import qf.sail.service.impl.AccountServiceImpl;
import qf.sail.vo.ResultVO;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * 用户登录
 */
@WebServlet("/login")
public class LoginServlet extends BaseServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String phone = req.getParameter("phone");
        String password = req.getParameter("password");
        AccountService accountService = new AccountServiceImpl();

        Account account = accountService.findAccountByPhone(phone);
        if(account == null){
            //用户不存在
            repError(resp, CodeMsg.NOT_ACCOUNT);
            return;
        }
        if(!account.getPassword().equals(password)){
            repError(resp,CodeMsg.PASSWORD_ERR);
            return;
        }
        System.out.println("登录成功");

//        //计算用户数
//        List userList = (List) req.getServletContext().getAttribute("userList");
//        if(userList == null || userList.size() == 0){
//            userList = new ArrayList();
//            userList.add(userName);
//            req.getServletContext().setAttribute("userList",userList);
//            req.getServletContext().setAttribute("accountCount",1);
//        }else{
//            boolean hasAccount = userList.stream().anyMatch(item -> userName.equals(item));
//            if(!hasAccount){
//                userList.add(userName);
//                req.getServletContext().setAttribute("userList",userList);
//                req.getServletContext().setAttribute("accountCount",userList.size());
//            }
//        }

        req.getSession().setAttribute("account",account);
        ResultVO resultVO = new ResultVO();
        resultVO.addData("account",account);
        repSuccess(resp,resultVO);
    }
}
